package br.edu.ufcg.lsd.wbis.ui.client.ui.loggedin.admin.home.authorization;

import java.util.List;

import br.edu.ufcg.lsd.wbis.ui.client.beans.UserInfo;
import br.edu.ufcg.lsd.wbis.ui.client.services.UserService;
import br.edu.ufcg.lsd.wbis.ui.client.ui.loggedin.admin.UserInfoPanel;
import br.edu.ufcg.lsd.wbis.ui.client.ui.loggedin.util.Randomizer;
import br.edu.ufcg.lsd.wbis.ui.client.ui.loggedin.util.RandomizerToolbar;
import br.edu.ufcg.lsd.wbis.ui.client.ui.management.InfoManager;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.TabPanel;
import com.gwtext.client.widgets.layout.ColumnLayout;
import com.gwtext.client.widgets.portal.Portlet;

/**
 * @author Renato Miceli
 */
public class UnauthorizedUsersPortlet extends Portlet implements Randomizer {

	private class UserAuthorizerCallback implements AsyncCallback<List<UserInfo>> {

		/**
		 * {@inheritDoc}
		 */
		public void onFailure(Throwable caught) {
			// Do nothing!
		}

		/**
		 * {@inheritDoc}
		 */
		public void onSuccess(List<UserInfo> result) {
			for (int i = 0; i < UnauthorizedUsersPortlet.this.userInfoViewerPanels.length; i++) {
				userInfoViewerPanels[i].updateInfo(result.get(i % result.size()));
			}
		}

	}

	private static class UserInfoViewerPanel extends Panel {

		private final UserInfoPanel infoPanel;

		private final UnauthorizedUserInfoViewerToolbar viewerToolbar;

		public UserInfoViewerPanel(UnauthorizedUsersPortlet randomizer, TabPanel centerPanel, InfoManager<UserInfo> manager) {

			this.infoPanel = new UserInfoPanel();
			this.viewerToolbar = new UnauthorizedUserInfoViewerToolbar(manager, randomizer, centerPanel);

			this.setLayout(new ColumnLayout());

			this.add(this.infoPanel);
			this.add(this.viewerToolbar);
		}

		public void updateInfo(UserInfo info) {
			this.infoPanel.updateInfo(info);
			this.viewerToolbar.updateInfo(info);
		}

	}

	private final UserInfoViewerPanel[] userInfoViewerPanels;

	private final InfoManager<UserInfo> manager;

	public UnauthorizedUsersPortlet(TabPanel centerPanel, InfoManager<UserInfo> manager) {

		this.manager = manager;

		this.setTitle("Unauthorized Users");
		this.setLayout(new ColumnLayout());

		this.userInfoViewerPanels = new UserInfoViewerPanel[] { new UserInfoViewerPanel(this, centerPanel, manager),
				new UserInfoViewerPanel(this, centerPanel, manager), new UserInfoViewerPanel(this, centerPanel, manager) };
		for (UserInfoViewerPanel panel : userInfoViewerPanels) {
			this.add(panel);
		}

		this.add(new RandomizerToolbar(this));

		this.randomize();
	}

	public void randomize() {
		UserService.Util.getInstance().getRandomUnauthorizedUserInfos(manager.getInfo(), new UserAuthorizerCallback());
	}

}
